#!/usr/bin/perl
#!/usr/local/bin/perl
###################################
# log_cutting.pl: created by Lihy #
###################################
# It cuts part of the source log into new log with a fixed period.
# Each time when cutting, it starts from the position recorded last time copying the rest content
# to a new log file, and updates the next start position to the end position of file.

use strict;
use warnings;

our $LOG = "access.log";                  #source log
our $CUTTED_LOG_DIR = "cutted_logs";      #dir containing cutted logs
my $cut_period = 60;                      #the period for cutting log
my $pos = 0;                              #the next start position

-e $LOG or die "Log file doesn't exist.\n";
-e $CUTTED_LOG_DIR 
  or mkdir $CUTTED_LOG_DIR
  or die "Can't create cutted logs dir.\n";

while(1)
{
  my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
  $year += 1900;
  $mon += 1;
  my $newlog = sprintf ("%s/access_%d-%d-%d-%d-%d.log",
                         $CUTTED_LOG_DIR,$year,$mon,$mday,$hour,$min);
  
  open INFILE, "<", $LOG
    or die "$0: Couldn't open input log file,$!";
  open OUTFILE, ">", $newlog
    or die "$0: Couldn't open output log file,$!";
  
  seek INFILE,$pos,0;
  while (<INFILE>) {
    print OUTFILE $_;
    $pos += length($_);
  }
  
  close INFILE;
  close OUTFILE;
  sleep $cut_period;
}
